package com.example.order_engine.domain.factory.impl;

import com.example.order_engine.domain.factory.OrderFactory;
import com.example.order_engine.domain.model.Order;
import com.example.order_engine.domain.model.OrderItem;
import com.example.order_engine.domain.model.OrderExtraInfo;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 标准订单工厂实现
 */
@Component
public class StandardOrderFactory implements OrderFactory {
    
    @Override
    public Order createOrder(Map<String, Object> orderRequest) {
        String orderId = UUID.randomUUID().toString();
        String orderType = (String) orderRequest.get("orderType");
        String customerId = (String) orderRequest.get("customerId");
        
        // 解析商品信息
        List<Map<String, Object>> itemsData = (List<Map<String, Object>>) orderRequest.get("items");
        List<OrderItem> items = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;
        
        for (Map<String, Object> itemData : itemsData) {
            String productId = (String) itemData.get("productId");
            String productName = (String) itemData.get("productName");
            BigDecimal price = new BigDecimal(itemData.get("price").toString());
            Integer quantity = (Integer) itemData.get("quantity");
            
            OrderItem item = new OrderItem(productId, productName, price, quantity);
            items.add(item);
            totalAmount = totalAmount.add(item.getSubtotal());
        }
        
        // 解析额外信息
        Map<String, Object> extraParams = (Map<String, Object>) orderRequest.get("extraInfo");
        OrderExtraInfo extraInfo = new OrderExtraInfo(extraParams);
        
        return new Order(orderId, orderType, customerId, totalAmount, items, extraInfo);
    }
    
    @Override
    public String getSupportedOrderType() {
        return "STANDARD";
    }
}